package services

import (
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"io/ioutil"
	"net/http"
	"purchase-mall/dao/pg"
	"purchase-mall/dao/redis"
	"purchase-mall/models"
	"purchase-mall/utils"
	"time"
)

//Tile {"token":"all","total":366682682,"resolveCount":0,"img":185971592,"vec":846573,"ter":1035367,"cia":166764086,"cat":137576,"terrain":5828854,"terrainRgb":0,"poi":166328,"baseDataInfo":5787092,"whiteModel":106724}
//CDN {"token":"all","total":210974323,"resolveCount":0,"img":120130829,"vec":621515,"ter":963392,"cia":88634777,"cat":30122,"terrain":593649,"terrainRgb":0,"poi":0,"baseDataInfo":0,"whiteModel":0}
type TileResp struct {
	Total int `json:"total"`
	Poi   int `json:"poi"`
}

type TileDorisResp struct {
	Success bool      `json:"success"`
	Msg     string    `json:"msg"`
	Data    DataDoris `json:"data"`
}

type DataDoris struct {
	SumCnt int `json:"sumCnt"`
}

func GetApiBase(url string) (body []byte, err error) {
	//redis 获取auth
	//dynamicAuthorization := "name=QfGs1XFq;client=RHn_79BFHVph"
	//dynamicAuthorization := "name=tdOOZ3yH;client=uM35bmyFSg3a"
	_, dynamicAuthorization := redis.GetAuth("dynamicAuthorization")
	//fmt.Printf("Redis Key IS dynamicAuthorization:%s\n", dynamicAuthorization)

	client := &http.Client{}
	request, err := http.NewRequest("GET", url, nil)
	request.Header.Add("authorization", dynamicAuthorization)

	resp, err := client.Do(request)
	if err != nil {
		zap.L().Error("MetricTile Http Api failed",
			zap.String("authorization", dynamicAuthorization),
			zap.Error(err))
		return
	}
	defer resp.Body.Close()

	body, err = ioutil.ReadAll(resp.Body)
	//fmt.Printf("API Result:%s\n", string(body))
	if err != nil {
		return nil, err
	}
	return
}

func TileTotalDoris(timeStart string, timeEnd string) (err error, infos *TileDorisResp) {
	url := utils.TileTotalDorisUrl
	url = fmt.Sprintf("%s?st=%s&et=%s", url, timeStart, timeEnd)
	//fmt.Printf("url:%s\n", url)
	body, _ := GetApiBase(url)
	//fmt.Printf("body Type %T", body)

	err = json.Unmarshal(body, &infos)
	if err != nil {
		return err, nil
	}
	//fmt.Printf("%v %#v\n", err, infos.Data.SumCnt)
	return
}

func TileTotal(timeStart string, timeEnd string) (err error, infos *TileResp) {
	url := utils.TileTotalUrl
	url = fmt.Sprintf("%s?st=%s&et=%s", url, timeStart, timeEnd)
	//fmt.Printf("url:%s\n", url)
	body, _ := GetApiBase(url)

	err = json.Unmarshal(body, &infos)
	if err != nil {
		return err, nil
	}
	//println(infos.Total)
	return
}

func CdnTotal(timeStart string, timeEnd string) (err error, infos *TileResp) {
	url := utils.CdnTotalUrl
	url = fmt.Sprintf("%s?st=%s&et=%s", url, timeStart, timeEnd)
	//fmt.Printf("url:%s\n", url)
	body, _ := GetApiBase(url)

	err = json.Unmarshal(body, &infos)
	if err != nil {
		return err, nil
	}
	//println(infos.Total)
	return
}

func MetricTileDoris(timeStart string, timeEnd string) (err error, aliyun *models.Aliyun) {
	_, tile := TileTotalDoris(timeStart, timeEnd)
	aliyun = &models.Aliyun{
		PeakValue:  float64(tile.Data.SumCnt),
		PeakTime:   timeStart,
		Period:     60,
		TypeName:   "ods_daas_log",
		MetricName: "log_total",
		MaxValue:   9999999999,
		CreatedAt:  time.Now().Format("2006-01-02 15:04:05"),
		StatDate:   timeStart,
		Instance:   "ods_daas_log",
		Host:       "svc.geoppt.com",
	}
	// 入库 pg
	if err = pg.InsertData(aliyun); err != nil {
		zap.L().Error("MetricTile.InsertData failed", zap.Error(err))
		return
	}
	return

}

func MetricTile(timeStart string, timeEnd string) (err error, aliyun *models.Aliyun) {
	_, tile := TileTotal(timeStart, timeEnd)
	_, cdn := CdnTotal(timeStart, timeEnd)

	aliyun = &models.Aliyun{
		PeakValue:  float64(tile.Total + cdn.Total - tile.Poi),
		PeakTime:   timeStart,
		Period:     60,
		TypeName:   "ods_daas_log",
		MetricName: "log_total",
		MaxValue:   9999999999,
		CreatedAt:  time.Now().Format("2006-01-02 15:04:05"),
		StatDate:   timeStart,
		Instance:   "ods_daas_log",
		Host:       "svc.geoppt.com",
	}
	// 入库 pg
	if err = pg.InsertData(aliyun); err != nil {
		zap.L().Error("MetricTile.InsertData failed", zap.Error(err))
		return
	}
	return

}
